#!/usr/bin/env python
# encoding:utf-8
'''
@author: yangyongjie
@license: (C) Copyright 2013-2017, Node Supply Chain Manager Corporation Limited. 
@contact: deamoncao100@gmail.com
software: garner
@file: user.py
@time: 2022/8/26 20:12
@desc:
'''
from model import db
import datetime
from werkzeug.security import generate_password_hash

class UserManager(db.Model):
    __tablename__ = "user"   # 映射的数据表，不写的话，默认是类名
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(128), nullable=False)
    _password = db.Column("password", db.String(512), nullable=False)
    email = db.Column(db.String(128), nullable=False)
    phone_number = db.Column(db.String(24), nullable=False)
    role = db.Column(db.Integer, nullable=False)
    CreateAt = db.Column(db.DateTime, default=datetime.datetime.now())

    order = db.relationship("Orders", backref="username")
    def keys(self):
        return ('username', 'password', 'email', 'phone_number', 'role', "CreateAt")

    def __getitem__(self, item):
        return getattr(self, item)

    def to_json(self):
        return {
            "username": self.username,
            "password": self.password,
            "email": self.email
        }
    # 属性包装
    # 把方法当作属性一样使用
    # #定义一些属性之前做一些检测，转换
    @property  # -----> 生成 password.setter  password.deleter
    def password(self):
        return self._password
    # user.password()   ---》 print(user.password)

    #user.password = xxxx
    @password.setter
    def password(self, value):
        self._password = generate_password_hash(value)

    @classmethod
    def create_user(cls, username, password, email, phone_number, role):
        user = cls()
        user.username = username
        user.password = password
        #user._password = generate_password_hash(value)
        #user._password = value
        user.email = email
        user.phone_number = phone_number
        user.role = role
        db.session.add(user)
        db.session.commit()

# 多对多的关系
app_permission = db.Table("app_permission",
                          db.Column("api_id",db.ForeignKey("api_token.id")),
                          db.Column("permission_id",db.ForeignKey("api_permission.id"))
                          )
# api_token表
# 存放的是授权密钥，以及授权id
class ApiToken(db.Model):
    __tablename__ = "api_token"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    appid = db.Column(db.String(128), nullable=False)
    secretkey = db.Column(db.String(128), nullable=False)
    #通过中间表去创建多对多的关系
    manage = db.relationship("ApiPermission", secondary=app_permission, backref="token")

# 存放的是授权的url
class ApiPermission(db.Model):
    __tablename__ = "api_permission"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    url = db.Column(db.String(128), nullable=False)
    method_type = db.Column(db.String(128), nullable=False)
